<template>
  <el-collapse-item name="7">
    <template #title>
      <h2>定时器</h2>
    </template>
    <div v-if="config.server">
      <h3>任务数量: {{ config.server.user_timer?.length }}</h3>

      <el-collapse
        :expand-icon-position="'left'"
        accordion
        v-if="config.server.user_timer?.length"
      >
        <el-collapse-item
          v-for="(task, index) in config.server.user_timer"
          :key="task.name + index"
          :name="index"
        >
          <template #title>
            <el-row align="middle" style="width: 100%">
              <el-col :span="4">
                <b>任务名</b>
              </el-col>
              <el-col :span="15" @click.stop="">
                <el-input
                  v-model="task.name"
                  style="width: 100%"
                  :placeholder="`请输入任务名`"
                  :maxlength="16"
                />
              </el-col>
              <el-col :span="4" @click.stop="">
                <el-switch v-model="task.enable" :active-value="1" :inactive-value="0" />
              </el-col>
            </el-row>
          </template>

          <el-row align="middle" style="margin-top: 10px">
            <el-col :span="4">
              <b>类型</b>
            </el-col>
            <el-col :span="7">
              <el-select-v2
                v-model="task.type"
                :options="type2str"
                placeholder="请选择定时器类型"
              />
            </el-col>
            <el-col :span="4" :offset="1">
              <b>时间类型</b>
            </el-col>
            <el-col :span="7">
              <el-select-v2
                v-model="task.time_type"
                :options="timeType2str"
                placeholder="请选择时间类型"
              />
            </el-col>
          </el-row>

          <el-row
            v-if="task.type == 2"
            align="middle"
            style="margin-top: 10px; justify-content: center"
          >
            <el-checkbox-group v-model="task.weekday" size="large">
              <el-checkbox-button
                v-for="day in weekdays2str"
                :key="day.label"
                :value="day.value"
              >
                {{ day.label }}
              </el-checkbox-button>
            </el-checkbox-group>
          </el-row>

          <el-row
            v-if="task.time_type == 0"
            align="middle"
            style="margin-top: 10px; justify-content: space-evenly"
          >
            <el-col :span="2">
              <el-text>从</el-text>
            </el-col>
            <el-col :span="5">
              <el-select-v2
                v-model="task.start.hour"
                :options="hour_options"
                placeholder="小时"
              />
            </el-col>
            <el-col :span="5">
              <el-select-v2
                v-model="task.start.minute"
                :options="minute_options"
                placeholder="分钟"
              />
            </el-col>
            <el-col :span="2">
              <el-text>到</el-text>
            </el-col>
            <el-col :span="5">
              <el-select-v2
                v-model="task.end.hour"
                :options="hour_options"
                placeholder="小时"
              />
            </el-col>
            <el-col :span="5">
              <el-select-v2
                v-model="task.end.minute"
                :options="minute_options"
                placeholder="分钟"
              />
            </el-col>
          </el-row>

          <div v-if="actions.list.length" v-for="action_type in ['start', 'end']">
            <h3>{{ action_type == "start" ? "开始动作" : "结束动作" }}</h3>

            <el-row
              align="middle"
              style="margin-top: 10px; justify-content: space-evenly"
            >
              <el-col :span="4">
                <b>动作</b>
              </el-col>
              <el-col :span="20">
                <el-select-v2
                  v-model="task[action_type].action.name"
                  filterable
                  :options="actions.list"
                  placeholder="请选择动作"
                />
              </el-col>
            </el-row>

            <el-row
              align="middle"
              style="margin-top: 10px; justify-content: space-evenly"
              v-if="typeof actions[task[action_type].action.name] == 'number'"
            >
              <el-col :span="4">
                <b>句柄</b>
              </el-col>
              <el-col :span="20">
                <el-select-v2
                  v-model="task[action_type].action.handle"
                  filterable
                  :options="handle_list[actions[task[action_type].action.name]]"
                  placeholder="请选择句柄"
                >
                  <template #default="{ item }">
                    <span style="margin-right: 8px">{{ item.label }}</span>
                    <span style="color: var(--el-text-color-secondary); font-size: 13px">
                      {{ item.name }} : {{ item.desc }}
                    </span>
                  </template>
                </el-select-v2>
              </el-col>
            </el-row>

            <el-row
              align="middle"
              style="margin-top: 10px; justify-content: space-evenly"
              v-if="typeof actions[task[action_type].action.name] == 'number'"
            >
              <el-col :span="4">
                <b>参数</b>
              </el-col>
              <el-col :span="20">
                <el-select-v2
                  v-model="task[action_type].action.param"
                  filterable
                  :options="param_list[actions[task[action_type].action.name]]"
                  placeholder="请选择动作句柄参数"
                >
                  <template #default="{ item }">
                    <span style="margin-right: 8px">{{ item.label }}</span>
                    <span style="color: var(--el-text-color-secondary); font-size: 13px">
                      {{ item.name }} : {{ item.desc }}
                    </span>
                  </template>
                </el-select-v2>
              </el-col>
            </el-row>
          </div>
          <br />

          <el-popconfirm
            :title="'请确认是否删除' + task.name + '定时器任务'"
            confirm-button-text="确认"
            cancel-button-text="取消"
            @confirm="delete_timer_task(index)"
          >
            <template #reference>
              <el-button type="danger" circle size="large" :icon="CloseBold" />
            </template>
          </el-popconfirm>
        </el-collapse-item>
      </el-collapse>
    </div>

    <br />

    <el-tooltip
      effect="dark"
      content="添加定时任务"
      placement="top"
      v-if="config.server.user_timer.length < 10"
    >
      <el-button
        type="success"
        size="large"
        circle
        :icon="Plus"
        style="font-size: 2em"
        v-on:click="add_timer_task"
      />
    </el-tooltip>

    <div v-if="change">
      <el-button
        type="primary"
        style="margin-top: 10px; width: 90%"
        :loading="server_api.ticks?.timer_update_config > 0"
        @click="save"
      >
        保存
      </el-button>
    </div>
  </el-collapse-item>
</template>
<script setup lang="ts">
import store from "~/utils/store";
import server_api from "~/utils/server_api";
import { Plus, CloseBold } from "@element-plus/icons-vue";
const config = toRef(store);

const change = computed(() => {
  return (
    JSON.stringify(config.value.server.timer) !=
    JSON.stringify(config.value.server.user_timer)
  );
});

const type2str = [
  { label: "一次", value: 0 },
  { label: "每天", value: 1 },
  { label: "每周", value: 2 },
];

const timeType2str = [
  { label: "时间", value: 0 },
  { label: "日出日落", value: 1 },
];

const weekdays2str = [
  { label: "日", value: 1 },
  { label: "一", value: 2 },
  { label: "二", value: 3 },
  { label: "三", value: 4 },
  { label: "四", value: 5 },
  { label: "五", value: 6 },
  { label: "六", value: 7 },
];

const hour_options = Array.from({ length: 24 }).map((_, idx) => ({
  value: idx,
  label: idx,
}));

const minute_options = Array.from({ length: 60 }).map((_, idx) => ({
  value: idx,
  label: idx,
}));

const actions = computed(() => {
  let res = { list: [] };
  let len = config.value.server?.timer_action_list?.length;
  if (!len) return res;
  for (let item of config.value.server?.timer_action_list) {
    res[item.name] = res.list.length;
    let desc = item.desc_i18n ? item.desc_i18n : item.desc;
    res.list.push({
      label: `${item.name} ${desc ? "-" + desc : ""}`,
      value: item.name,
      id: res.list.length,
    });
  }
  return res;
});

const handle_list = computed(() => {
  let res = [];
  let len = config.value.server?.timer_action_list?.length;
  if (!len) return res;

  for (let item of config.value.server?.timer_action_list) {
    let handles = [];
    for (let handle of item.handle) {
      handles.push({
        name: item.name,
        label: handle.i18n ? handle.i18n : handle.name,
        value: handles.length,
        desc: handle.desc_i18n,
        id: res.length,
      });
    }
    res.push(handles);
  }
  return res;
});

const param_list = computed(() => {
  let res = [];
  let len = config.value.server?.timer_action_list?.length;
  if (!len) return res;
  for (let item of config.value.server?.timer_action_list) {
    let params = [];
    for (let param of item.params) {
      params.push({
        name: item.name,
        label: param.i18n ? param.i18n : param.name,
        value: params.length,
        id: res.length,
        desc: param.value,
      });
    }
    res.push(params);
  }
  return res;
});

const delete_timer_task = (idx: number) => {
  config.value.server.user_timer.splice(idx, 1);
};

const add_timer_task = () => {
  config.value.server.user_timer.push({
    name: `task - ${config.value.server.user_timer.length}`,
    enable: 0,
    type: 0,
    time_type: 0,
    weekday: [],
    start: {
      hour: 6,
      minute: 30,
      action: {
        name: "",
        handle: 0,
        param: 0,
      },
    },
    end: {
      hour: 19,
      minute: 0,
      action: {
        name: "",
        handle: 0,
        param: 0,
      },
    },
  });
};

const save = () => {
  let cfg = JSON.parse(JSON.stringify(config.value.server.user_timer));
  for (let item of cfg) {
    item.weekdays = 0;
    for (let bit = 0; bit < 7; bit++) {
      if (item.weekday[bit]) {
        item.weekdays |= 1 << (item.weekday[bit] - 1);
      }
    }
    delete item.time;
    delete item.weekday;
  }
  server_api.timer_update_config(cfg);
};
</script>
<style scoped></style>
